package me.hl;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import me.hl.handler.NettyServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Planck on 2016/2/25.
 */
public class NettyServerBootstrap {
    private static Logger logger = LoggerFactory.getLogger(NettyServerBootstrap.class);

    private int port;

    public NettyServerBootstrap(int port) {
        this.port = port;
        bind();
    }

    private void bind(){
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();

        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss,work);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.option(ChannelOption.SO_BACKLOG,1024);//这个是连接数
            bootstrap.option(ChannelOption.TCP_NODELAY,true);//立即发送消息
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE,true); //长连接
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new NettyServerHandler());
                }
            });
            ChannelFuture f = bootstrap.bind(port).sync();
            if (f.isSuccess()) {
                logger.debug("启动Netty服务成功，端口号：" + this.port);
            }
            f.channel().closeFuture().sync();

        }catch (Exception e){
            logger.error("启动Netty服务异常，异常信息：" + e.getMessage());
        }finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }


    }

    public static void main(String args[]){
        NettyServerBootstrap server = new NettyServerBootstrap(9999);
    }


}
